package com.mtbu.dao.base;
import my.myorm.tool.jdbc.RowMapper;
import my.myorm.tool.jdbc.SQLExecutor;
import my.myorm.tool.jdbc.SQLManager;
import my.myorm.tool.orm.TableBeanMap;
import java.sql.ResultSet;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import com.mtbu.bean.Step;
public abstract class  StepDaoBase implements RowMapper{
      private String dsName = "";
      public void setDsName(String dsName){
      		this.dsName=dsName;
      }
      public String getDsName(){
      		return this.dsName;
      }
      private String table;
      public void setTable(String table){
      		this.table = table;
      }
      public String getTable(){
      		if(table==null){
      			table = TableBeanMap.getBeanTable(Step.class);
      		}
      		return table;
      }
	private String toSaveSql(SQLExecutor dbconn,Step step,String split) throws Exception{
		if(split==null) split="";
		if(split.trim().equals("")) split=getSplit(step);
		Map<String,Object> dirtyProperties=step.getDirtyProperties();
		if(dirtyProperties.size() == 0) return "";
		StringBuffer sb=new StringBuffer();
		sb.append("insert into " + getTable() + split + " (");
		String[] props = dirtyProperties.keySet().toArray(new String[0]);
		for(int i = 0; i < props.length; i++) {
		      String prop = props[i];
		      String column = TableBeanMap.getColumnName(getTable(), prop);
		      sb.append(" ").append("`" + column + "`");
		      dbconn.addParam(dirtyProperties.get(prop));
		      if(i < props.length - 1) {
		          sb.append(",");
		      }
				}
		 sb.append(" ) values (");
		 for(int i = 0; i < props.length; i++) {
		    sb.append("?");
		     if(i < props.length - 1) {
		         sb.append(",");
		     }
		 }
		 sb.append(")");
		 //dirtyProperties.clear();
		 return sb.toString();
    }
    private String toUpdateSql(SQLExecutor dbconn,String byProperty,Step step,String split) throws Exception{
       if(split==null) split="";
      if(split.trim().equals("")) split=getSplit(step);
       Map<String,Object> dirtyProperties=step.getDirtyProperties();
       if(dirtyProperties.size() == 0) return "";
        String byColumn = TableBeanMap.getColumnName(step.getClass(), byProperty);
        if(byColumn == null) throw new Exception("byColumn==null");
        StringBuffer sb=new StringBuffer();
        sb.append("update  " + getTable() + split + " set ");
        String[] props = dirtyProperties.keySet().toArray(new String[0]);
        for(int i = 0; i < props.length; i++) {
            String prop = props[i];
            String column = TableBeanMap.getColumnName(getTable(), prop);
            sb.append(" ").append(column).append("=?");
            dbconn.addParam(dirtyProperties.get(prop));
            if(i < props.length - 1) {
                sb.append(",");
            }
        }
        sb.append(" where " + byColumn + "=?");
        //dirtyProperties.clear();
        return sb.toString();
    }
    private String toDeleteSql(String byProperty,Step step,String split) throws Exception{
      if(split==null) split="";
      if(split.trim().equals("")) split=getSplit(step);
        String byColumn=TableBeanMap.getColumnName(step.getClass(),byProperty);
        if(byColumn==null) throw new Exception("byColumn==null");
        String sql="delete from "+getTable()+split+" where "+byColumn+"=?";
        return sql;
    }
    public void save(Step step,boolean withoutTransaction,String split) throws Exception{
             if(step==null) return;
             SQLExecutor dbconn= SQLManager.getSQLExecutor(dsName,withoutTransaction);
              String sql=this.toSaveSql(dbconn,step,split);
              if(sql.equals("")) return;
            step.setId((int)dbconn.execute(sql,true));
    }
    public void save(Step step,boolean withoutTransaction) throws Exception{
            save(step,withoutTransaction,null);
    }
    public void save(Step step,String split) throws Exception{
            if(step==null) return;
             SQLExecutor dbconn= SQLManager.getSQLExecutor(dsName);
              String sql=this.toSaveSql(dbconn,step,split);
              if(sql.equals("")) return;
            if(step.getId()==0){
            	step.setId((int)dbconn.execute(sql,true));
            }else{
           		dbconn.execute(sql); 	
            }  
    }
    public void save(Step step) throws Exception{
            save(step,null);
    }
    public int update(Step step,String split) throws Exception{
           return update(null,step,split);
    }
    public int update(Step step) throws Exception{
           return update(step,null);
    }
     public int update(String byProperty,Step step,String split) throws Exception{
        if(step==null) return 0;
        SQLExecutor dbconn= SQLManager.getSQLExecutor(dsName);
        if(byProperty==null||byProperty.equals("")){
            byProperty=getDefaultKeyProperty();
        }
        String sql=this.toUpdateSql(dbconn,byProperty,step,split);
        if(sql.equals("")) return 0;
        dbconn.addParam(getPropertyValue(step,byProperty));
        int result= (int)dbconn.execute(sql);
         return result;
    }
    public int update(String byProperty,Step step) throws Exception{
        return update(byProperty,step,null);
    }
     public int update(Step step,boolean withoutTransaction,String split) throws Exception{
            return update(null,step,withoutTransaction,split);
    }
     public int update(Step step,boolean withoutTransaction) throws Exception{
            return update(step,withoutTransaction,null);
    }
    public int update(String byProperty,Step step,boolean withoutTransaction,String split) throws Exception{
        if(step==null) return 0;
        SQLExecutor dbconn= SQLManager.getSQLExecutor(dsName,withoutTransaction);
        if(byProperty==null||byProperty.equals("")){
            byProperty=getDefaultKeyProperty();
        }
        String sql=this.toUpdateSql(dbconn,byProperty,step,split);
        if(sql.equals("")) return 0;
        dbconn.addParam(getPropertyValue(step,byProperty));
        int result= (int)dbconn.execute(sql);
         return result;
    }
    public int update(String byProperty,Step step,boolean withoutTransaction) throws Exception{
       return  update(byProperty,step,withoutTransaction,null);
    }
    public int delete(String byProperty,Step step,String split) throws Exception{
          if(step==null) return 0;
        SQLExecutor dbconn= SQLManager.getSQLExecutor(dsName);
        if(byProperty==null||byProperty.equals("")){
            byProperty=getDefaultKeyProperty();
        }
        String sql=this.toDeleteSql(byProperty,step,split);
        dbconn.addParam(getPropertyValue(step,byProperty));
        int result=(int)dbconn.execute(sql);
        return result;
    }
    public int delete(String byProperty, Object param, String split) throws Exception {
        if(param == null) return 0;
        SQLExecutor dbconn = SQLManager.getSQLExecutor(dsName);
        if(byProperty == null || byProperty.equals("")) {
            byProperty = getDefaultKeyProperty();
        }
        String sql = "delete from " + getTable() + split + " where " + byProperty + "=?";
        dbconn.addParam(param);
        int result = (int) dbconn.execute(sql);
        return result;
    }
    public int delete(Object param) throws Exception {
        return delete(null, param, null);
    }
    public int delete(String byProperty,Step step) throws Exception{
          return  delete(byProperty,step,null);
    }
     public int delete(Step step,String split) throws Exception{
          return delete(null,step,split);
    }
    public int delete(Step step) throws Exception{
          return delete(step,null);
    }
    public int delete(Step step,boolean withoutTransaction,String split) throws Exception{
         return delete(null,step,withoutTransaction,split);
    }
    public int delete(Step step,boolean withoutTransaction) throws Exception{
         return delete(step, withoutTransaction,null);
    }
    public int delete(String byProperty,Step step,boolean withoutTransaction,String split) throws Exception{
        if(step==null) return 0;
        SQLExecutor dbconn= SQLManager.getSQLExecutor(dsName,withoutTransaction);
        if(byProperty==null||byProperty.equals("")){
            byProperty=getDefaultKeyProperty();
        }
        String sql=this.toDeleteSql(byProperty,step,split);
        dbconn.addParam(getPropertyValue(step,byProperty));
        int result=(int)dbconn.execute(sql);
        return result;
    }
    public int delete(String byProperty,Step step,boolean withoutTransaction) throws Exception{
        return  delete(byProperty,step,withoutTransaction,null);
    }
     public Step findStep(Object param) throws Exception{
           return findStep(null,param,null);
    }
     public Step findStep(Object param,boolean notNull) throws Exception{
    	 Step result = findStep(null,param,null);    	 
         return result == null ? (notNull ? new Step() : null) : result;
    }
    public Step findStep(String byProperty,Object param,String split) throws Exception{
        if(byProperty==null||byProperty.trim().equals("")) byProperty=getDefaultKeyProperty();
        if(split==null) split="";
        split=split.trim();
        String byColumn = TableBeanMap.getColumnName(Step.class, byProperty);
        String sql="select * from " + getTable() + split + " where " + byColumn + "=?";
        SQLExecutor dbconn= SQLManager.getSQLExecutor(dsName,true);
        dbconn.addParam(param);
        return dbconn.queryForBean(sql,Step.class);
    }
    private String getDefaultKeyProperty(){
           return "id";
    }
    private Object getPropertyValue(Step step,String propertyName) throws Exception{
    if(propertyName==null||propertyName.equals("")) return null;
           if(propertyName.equalsIgnoreCase("id")){
                return step.getId();
           }
           if(propertyName.equalsIgnoreCase("type")){
                return step.getType();
           }
           if(propertyName.equalsIgnoreCase("status")){
                return step.getStatus();
           }
           if(propertyName.equalsIgnoreCase("createTime")){
                return step.getCreateTime();
           }
           if(propertyName.equalsIgnoreCase("updateTime")){
                return step.getUpdateTime();
           }
           if(propertyName.equalsIgnoreCase("beanName")){
                return step.getBeanName();
           }
           if(propertyName.equalsIgnoreCase("nextStepId")){
                return step.getNextStepId();
           }
           if(propertyName.equalsIgnoreCase("preStepId")){
                return step.getPreStepId();
           }
           if(propertyName.equalsIgnoreCase("projectId")){
                return step.getProjectId();
           }
           if(propertyName.equalsIgnoreCase("name")){
                return step.getName();
           }
           return null;
    }
    public Object mapRow(ResultSet rs, Map<String, String> columns) throws Exception {
        Step step=new Step();
         Map<String,Object> valueMap=new HashMap<String,Object>();
         String[] lables=columns.keySet().toArray(new String[0]); 
         String table=getTable();
         for(int i=0;i < lables.length;i++){
              String propertyName= TableBeanMap.getPropertName(table,columns.get(lables[i]));
              Object value=rs.getObject(lables[i]);
              if(value==null) continue;
              if(value instanceof java.sql.Date){
                          java.sql.Date o=(java.sql.Date)value;
                          value=new Date(o.getTime());
              }else if(value instanceof java.sql.Time){
                          java.sql.Time o=(java.sql.Time)value;
                          value=new Date(o.getTime());
              }else if(value instanceof java.sql.Timestamp){
                          java.sql.Timestamp o=(java.sql.Timestamp)value;
                          value=new Date(o.getTime());
               }else if(value instanceof java.math.BigDecimal){
                          value=((java.math.BigDecimal)value).doubleValue();
               }else if(value instanceof java.math.BigInteger){
                          value=((java.math.BigInteger)value).longValue();
               }
               valueMap.put(propertyName,value);
         }
         loadFromMap(valueMap,step);
         valueMap=null;
         return step;
    }
    private void loadFromMap(Map<String,Object> valueMap,Step step) throws Exception{
        if(valueMap.containsKey("id")){
             step.setId((java.lang.Integer)valueMap.get("id"));
        }
        if(valueMap.containsKey("type")){
             step.setType((java.lang.Integer)valueMap.get("type"));
        }
        if(valueMap.containsKey("status")){
             step.setStatus((java.lang.Integer)valueMap.get("status"));
        }
        if(valueMap.containsKey("createTime")){
             step.setCreateTime((java.util.Date)valueMap.get("createTime"));
        }
        if(valueMap.containsKey("updateTime")){
             step.setUpdateTime((java.util.Date)valueMap.get("updateTime"));
        }
        if(valueMap.containsKey("beanName")){
             step.setBeanName((java.lang.String)valueMap.get("beanName"));
        }
        if(valueMap.containsKey("nextStepId")){
             step.setNextStepId((java.lang.Integer)valueMap.get("nextStepId"));
        }
        if(valueMap.containsKey("preStepId")){
             step.setPreStepId((java.lang.Integer)valueMap.get("preStepId"));
        }
        if(valueMap.containsKey("projectId")){
             step.setProjectId((java.lang.Integer)valueMap.get("projectId"));
        }
        if(valueMap.containsKey("name")){
             step.setName((java.lang.String)valueMap.get("name"));
        }
    }
    public JSONObject toJSON(Step step)  throws Exception{
        if(step==null) return null;
        return step.toJSON();
    }
    public Step fromJSON(JSONObject json) throws Exception{
       if(json==null) return null;
       Step step=new  Step();
        step.fromJSON(json);
        return step;
    }
   public Step fromMap(Map<String,String> paramMap) throws Exception{
       Step step=new  Step();
       if(paramMap!=null){
           Map<String,String> beanmap=new HashMap<String,String>();
           Iterator it = paramMap.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String key = (String) entry.getKey();
                String value =(String)entry.getValue();
                if(key==null) continue;
                int dotindex=key.indexOf(".");
                if(dotindex>-1){
                    String beanname=key.substring(0,dotindex);
                    String propname=key.substring(dotindex+1);
                    if(beanname.equalsIgnoreCase("Step")){
                        beanmap.put(propname.toLowerCase(),value);
                    }
                }else{
                    beanmap.put(key.toLowerCase(),value);
                }
            }
           step.fromMap(beanmap);
       }
        return step;
    }
    public abstract String getSplit(Step step) throws Exception;
}
